package me.tonywang.common.util;

import org.springframework.core.io.Resource;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @className: ScriptEngineUtils
 * @description:
 * @author: WANGHUI
 * @createDate: 2018/5/10 11:49
 * @version: 1.0
 */
public class ScriptEngineUtils {

    public static final String GET_VALUE_FUNCTION = "getValue";

    private static ScriptEngine se;

    private static final String RESOURCE_PATTERN = "/js/*.js";

    /*
     * JS ScriptEngine 因初始化过程很耗时，类加载时即完成初始
     */
    static {
        se = new ScriptEngineManager().getEngineByName("javascript");
        Resource[] resources = ResourceUtils.getResourcesFromClassPath(RESOURCE_PATTERN);
        if (resources != null) {
            for (Resource resource : resources) {
                try {
                    se.eval(new InputStreamReader(resource.getInputStream()));//获取classpath下的js文件
                } catch (Exception e) {
                    //
                }
            }
        }

        try {
            String script = " function " + GET_VALUE_FUNCTION + "( REQ , condVal ) {  return eval( condVal ) ; } ";
            se.eval(script);
        } catch (ScriptException e) {
//            e.printStackTrace();
        }
    }

    /**
     * @param jsonObj JAVAbean对象
     * @param condVal
     * @return
     */
    public static Object eval(Object jsonObj, String condVal) {
        Invocable jsInvocable = (Invocable) se;
        Object obj = null;
        try {
            obj = jsInvocable.invokeFunction(GET_VALUE_FUNCTION, jsonObj, condVal);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }


    /**
     * @return
     * @throws IOException
     * @throws ScriptException
     */
    public static Object eval(String invokeFunction, Object... args) {
        Invocable jsInvocable = (Invocable) se;
        Object obj = null;
        try {
            obj = jsInvocable.invokeFunction(invokeFunction, args);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }


}
